package cn.hairui.blog.mapper;

import cn.hairui.blog.model.Message;
import cn.hairui.blog.model.Messagereply;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * <h2>请添加说明
 * </h2>
 * <ol>请添加详细说明
 * </ol>
 *
 * <h2>修改历史
 * </h2>
 * <ol>如有修改，请添加修改历史
 * </ol>
 *
 * </p>
 *
 * @author laoganbu
 * @version V1.0
 * @date 2019/7/29 18:41
 */
@Mapper
public interface MessageMapper {

    @Select("SELECT T1.*,T2.NICKNAME,T2.PROPHOTO FROM MESSAGE T1 LEFT JOIN USER T2 ON T1.USERNAME=T2.USERNAME WHERE T1.STATUS=#{status} ORDER BY T1.ID DESC LIMIT 0,#{count}")
    List<Map> findLimited(String status, int count);

    @Select("SELECT * FROM MESSAGE ORDER BY ID DESC")
    List<Message> list();

    @Select("SELECT T1.ID AS id ,T1.USERNAME AS account,(SELECT T2.NICKNAME  FROM USER T2 WHERE T1.USERNAME=T2.USERNAME LIMIT 1 ) AS name,(SELECT T2.PROPHOTO  FROM USER T2 WHERE T1.USERNAME=T2.USERNAME LIMIT 1 ) AS prophoto,T1.CONTENT AS content,T1.MESSAGE_TIME AS time FROM MESSAGE T1 WHERE T1.STATUS='1' ORDER BY T1.ID DESC ")
    List<Map> listMap();

    @Select("SELECT * FROM MESSAGE WHERE ID=#{id}")
    Message find(int id);

    @Insert("INSERT INTO MESSAGEREPLY " +
            "(MSGID,FROMUSER,TOUSER,CONTENT,REPLYTIME,STATUS) " +
            "VALUES" +
            "(#{msgid},#{fromuser},#{touser},#{content},#{replytime},#{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void addReply(Messagereply messagereply);

    @Insert("INSERT INTO MESSAGE " +
            "(USERNAME,CONTENT,MESSAGE_TIME,STATUS) " +
            "VALUES" +
            "(#{username},#{content},#{messageTime},#{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void add(Message message);

    @Select("select t1.id as id,t1.content as content,t1.msgid as msgid,t1.fromuser as fromuser,(select t2.nickname from user t2 where t1.fromuser=t2.username limit 1) as fromusername,(select t4.prophoto from user t4 where t1.fromuser=t4.username) as prophoto,t1.touser as touser,(select t3.nickname from user t3 where t1.touser=t3.username limit 1) as tousername,t1.replytime as replytime from messagereply t1 where t1.msgid=#{msgId} order by t1.id asc, t1.replytime asc")
    List<Map> listReply(int msgId);

    @Select("SELECT * FROM MESSAGEREPLY WHERE ID=#{id}")
    Messagereply findReply(int id);
}
